package com.h117121.fashionshop.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.h117121.fashionshop.controller.generic.GenericController;
import com.h117121.fashionshop.core.dom.Account;
import com.h117121.fashionshop.core.dom.Cart;

@Controller
@RequestMapping("/cart")
public class CartController extends GenericController {
	@RequestMapping(method = RequestMethod.GET)
	public String showPage(HttpServletRequest request) {
		Account account = (Account) request.getSession()
				.getAttribute("account");
		if (account == null) {
			return "redirect:/login";
		}
		return "CartPage";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String updateCart(HttpServletRequest request) {
		Account account = (Account) request.getSession()
				.getAttribute("account");
		if (account == null) {
			return "redirect:/login";
		}

		Cart cart = account.getCart();
		String[] productIdsString = request.getParameterValues("productId");
		String[] quantitiesString = request.getParameterValues("quantity");
		String[] removedProductIdsString = request
				.getParameterValues("removed");
		if (productIdsString != null) {
			for (int i = 0; i < productIdsString.length; i++) {
				cart.update(Long.parseLong(productIdsString[i]),
						Integer.parseInt(quantitiesString[i]));
			}
		}

		if (removedProductIdsString != null) {
			long[] removedProductIds = new long[removedProductIdsString.length];
			for (int i = 0; i < removedProductIds.length; i++) {
				removedProductIds[i] = Long
						.parseLong(removedProductIdsString[i]);
			}
			cart.remove(removedProductIds);
		}

		return "CartPage";
	}

}
